package com.zhangxin.aiInterview.manager.work_flow.full_process_interview_analyze;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.Data;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 全流程面试分析
 */
public class FullProcessInterviewAnalyze {
    @Data
    public static class InterviewEvaluation {
        // 专业知识水平
        private double professionalKnowledgeScore;
        private String professionalKnowledgeComment;

        // 技能匹配度
        private double skillMatchScore;
        private String skillMatchComment;

        //  语言表达能力
        private double communicationScore;
        private String communicationComment;

        // 逻辑思维能力
        private double logicalThinkingScore;
        private String logicalThinkingComment;

        //  应变抗压能力
        private double stressHandlingScore;
        private String stressHandlingComment;

        //职业潜能与成长性
        private Double potentialGrowthScore;
        private String potentialGrowthComment;

        //团队合作
        private String teamworkScore;
        private String teamworkComment;

        //  总分
        private double totalScore;
        private String totalGrade;
        private String summary;
    }

    public static void main(String[] args) throws Exception {
        System.out.println(analyzeFullProcessInterviewAnalyze(1L, 1L, 1L, 1L, 1L));
    }

    /**
     * 分析笔试结果
     *
     * @param resumeId
     * @param userId
     * @param examId
     * @return
     * @throws Exception
     */
    public static InterviewEvaluation analyzeFullProcessInterviewAnalyze(Long resumeId, Long userId, Long examId, Long aiInterviewId, Long hrInterviewId) throws Exception {

        URL url = new URL("https://api.dify.ai/v1/workflows/run");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // 必须设置的请求头
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "Bearer app-EGB1oVapcTrxMJfwTWRHD8QB");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "text/event-stream");

        // 关键连接配置
        conn.setDoOutput(true);
        conn.setChunkedStreamingMode(0); // 启用分块传输
        conn.setReadTimeout(0); // 禁用读取超时

        // 发送请求体
        String body = String.format(
                "{\"inputs\": {\"resumeId\": \"%s\", \"userId\": \"%s\", \"examId\": \"%s\", \"aiInterviewId\": \"%s\", \"hrInterviewId\": \"%s\"}, \"response_mode\": \"%s\", \"user\": \"%s\"}",
                resumeId, userId, examId, aiInterviewId, hrInterviewId, "streaming", "abc-123"
        );
        System.out.println("body: " + body);
        try (OutputStream os = conn.getOutputStream()) {
            os.write(body.getBytes(StandardCharsets.UTF_8));
        }

        // 处理流式响应
        String result = "";
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(conn.getInputStream()))) {

            String line;
            while ((line = reader.readLine()) != null) {
                // 跳过心跳包
                if ("event: ping".equals(line.trim())) {
                    continue;
                }

                // 只获取最后一部分的数据
                JSONObject jsonObject = extractOutputs(line);
                if(ObjUtil.isEmpty(jsonObject)) continue;
                assert jsonObject != null;
                result = jsonObject.toString();
            }
        }
        return parseInterviewEvaluation(result);
    }

    /**
     * 解析json数据
     * @param json
     * @return
     */
    public static InterviewEvaluation parseInterviewEvaluation(String json) {
        System.out.println("全流程面试分析结果原始json数据：  " + json);
        JSONObject root = JSONUtil.parseObj(json).getJSONObject("structured_output");

        InterviewEvaluation evaluation = new InterviewEvaluation();

        JSONObject professional = root.getJSONObject("专业知识水平");
        evaluation.setProfessionalKnowledgeScore(professional.getDouble("score"));
        evaluation.setProfessionalKnowledgeComment(professional.getStr("comment"));

        JSONObject skillMatch = root.getJSONObject("技能匹配度");
        evaluation.setSkillMatchScore(skillMatch.getDouble("score"));
        evaluation.setSkillMatchComment(skillMatch.getStr("comment"));

        JSONObject communication = root.getJSONObject("语言表达能力");
        evaluation.setCommunicationScore(communication.getDouble("score"));
        evaluation.setCommunicationComment(communication.getStr("comment"));

        JSONObject logic = root.getJSONObject("逻辑思维能力");
        evaluation.setLogicalThinkingScore(logic.getDouble("score"));
        evaluation.setLogicalThinkingComment(logic.getStr("comment"));

        JSONObject stress = root.getJSONObject("应变抗压能力");
        evaluation.setStressHandlingScore(stress.getDouble("score"));
        evaluation.setStressHandlingComment(stress.getStr("comment"));

        JSONObject potentialGrowth = root.getJSONObject("职业潜力与成长性");
        evaluation.setPotentialGrowthScore(potentialGrowth.getDouble("score"));
        evaluation.setPotentialGrowthComment(potentialGrowth.getStr("comment"));


        JSONObject teamwork = root.getJSONObject("团队协作");
        evaluation.setTeamworkScore(teamwork.getStr("score"));
        evaluation.setTeamworkComment(teamwork.getStr("comment"));

        JSONObject overall = root.getJSONObject("综合评价");
        evaluation.setTotalScore(overall.getDouble("total_score"));
        evaluation.setTotalGrade(overall.getStr("grade"));
        evaluation.setSummary(overall.getStr("summary"));

        return evaluation;
    }

    /**
     * 提取 workflow_finished 事件中的 outputs 数据
     *
     * @param sseEvent 原始事件字符串（如 "data: {...}"）
     * @return 成功返回 JSONObject 格式的 outputs，失败返回 null
     */
    public static JSONObject extractOutputs(String sseEvent) {
        // 1. 校验并去除 "data: " 前缀
        if (!sseEvent.startsWith("data: ")) {
            return null;
        }
        String jsonStr = sseEvent.substring(6).trim();

        // 2. 解析为 JSONObject
        JSONObject event = JSONUtil.parseObj(jsonStr);
        if (event == null) {
            return null;
        }

        // 3. 校验事件类型
        if (!"workflow_finished".equals(event.getStr("event"))) {
            return null;
        }

        // 4. 提取 outputs
        JSONObject data = event.getJSONObject("data");
        if (data == null) {
            return null;
        }
        return data.getJSONObject("outputs");
    }
}